/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState } from 'react';
import {
  Avatar,
  Button,
  Col,
  Form,
  Input,
  Row,
  Tabs,
  TabsProps,
  message,
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  MobileOutlined,
  MailOutlined,
} from '@ant-design/icons';
import logo from '/logo.svg';
import { useHistory } from 'react-router';
import { useSendSmsCode } from '@src/hooks';
import login from '@src/apis/login';
import { LOGIN_TYPE, opType } from '@src/const';
import { IUser } from '@src/types/account';
import { useDispatch } from 'react-redux';
import { updateUserInfo } from '@src/store/user';
import { updateUserCookies } from '@src/utils/account';
import { useUserInfo } from '@src/store/user/hooks';

const LOGIN_METHODS: TabsProps['items'] = [
  {
    label: '账号密码登录',
    key: LOGIN_TYPE.PASS_LOGIN,
  },
  {
    label: '手机验证码登录',
    key: LOGIN_TYPE.PHONE_LOGIN,
  },
];

const App: React.FC = () => {
  const [form] = Form.useForm();
  const history = useHistory();
  const dispatch = useDispatch();
  const userInfo = useUserInfo();
  // 登录方式
  const [loginMethod, setLoginMethod] = useState(LOGIN_TYPE.PASS_LOGIN);
  const [submitBtnloading, setSubmitBtnLoading] = useState(false);
  const {
    countdown,
    setCountdown,
    loading: codeBtnLoading,
    setLoading: setCodeBtnLoading,
    handleSendSmsCode,
  } = useSendSmsCode();

  // 登录过的直接返回
  useEffect(() => {
    if (userInfo.uid) {
      history.goBack();
    }
  }, [userInfo.uid]);

  const verifyMobile = (rule, val, callback) => {
    // 验证手机号
    if (!val) {
      callback();
    }
    const myReg = /^[1][3,4,5,7,8][0-9]{9}$/;
    const validateResult = myReg.test(val); // 自定义规则
    if (!validateResult) {
      callback('不合法的手机号!');
      return;
    }
    callback();
  };

  // 重置所有信息
  const resetState = () => {
    setSubmitBtnLoading(false);
    setCodeBtnLoading(false);
    setCountdown(0);
    form.resetFields();
  };

  const verifyCode = (rule, val, callback) => {
    // 验证验证码
    if (!val) {
      callback();
    }
    const myReg = /^[0-9]{6}$/;
    const validateResult = myReg.test(val);
    if (!validateResult) {
      callback('验证码为六位数！');
      return;
    }
    callback();
  };

  const goToRegister = () => {
    history.push('/register');
  };

  // 后续这里应该重定向到上一个页面
  const goToMain = () => {
    history.replace('/', {});
  };

  // 提交
  const submit = async (values: any) => {
    const { code, phoneNumber, username, password } = values;
    try {
      setSubmitBtnLoading(true);
      let accountInfo = {} as IUser;
      // 账号密码登录
      if (loginMethod === LOGIN_TYPE.PASS_LOGIN) {
        accountInfo = await login(LOGIN_TYPE.PASS_LOGIN, {
          username,
          password,
        });
      } else {
        accountInfo = await login(LOGIN_TYPE.PHONE_LOGIN, {
          phoneNumber,
          code,
        });
      }
      // 更新redux的用户信息
      dispatch(updateUserInfo('setUserInfo')(accountInfo));
      updateUserCookies(accountInfo.uid);
      message.success('登录成功');
      goToMain();
    } catch (error: any) {
      message.error(error.msg);
    } finally {
      setSubmitBtnLoading(false);
    }
  };

  return (
    <div className='h-full w-full bg-login-bg flex justify-center items-center text-[14px]'>
      <div className='w-[328px] h-auto'>
        <div style={{ textAlign: 'center' }}>
          <div className='flex pt-[20px] justify-center items-center'>
            <Avatar src={logo} />
            <span
              style={{
                lineHeight: '44px',
                fontSize: '33px',
                fontWeight: '600px',
              }}>
              smart AI
            </span>
          </div>
          <div className='my-8 text-gray-500'>做最懂您的智能助手</div>
        </div>
        <Tabs
          defaultActiveKey={LOGIN_TYPE.PASS_LOGIN}
          items={LOGIN_METHODS}
          onChange={(e) => {
            resetState();
            setLoginMethod(e as LOGIN_TYPE);
          }}
        />
        <Form
          form={form}
          name='normal_login'
          className='login-form'
          onFinish={submit}>
          {loginMethod === LOGIN_TYPE.PASS_LOGIN && (
            <>
              <Form.Item
                name='username'
                rules={[
                  {
                    required: loginMethod === LOGIN_TYPE.PASS_LOGIN,
                    message: '用户名是必填项!',
                  },
                ]}>
                <Input
                  allowClear
                  size='large'
                  prefix={
                    <UserOutlined
                      className='site-form-item-icon'
                      style={{ color: '#1890ff' }}
                    />
                  }
                  placeholder='请输入用户名'
                />
              </Form.Item>
              <Form.Item
                name='password'
                rules={[
                  {
                    required: loginMethod === LOGIN_TYPE.PASS_LOGIN,
                    message: '密码是必填项!',
                  },
                ]}>
                <Input.Password
                  size='large'
                  prefix={
                    <LockOutlined
                      className='site-form-item-icon'
                      style={{ color: '#1890ff' }}
                    />
                  }
                  type='password'
                  placeholder='请输入密码'
                />
              </Form.Item>
            </>
          )}
          {loginMethod === LOGIN_TYPE.PHONE_LOGIN && (
            <>
              <Form.Item
                name='phoneNumber'
                rules={[
                  {
                    required: loginMethod === LOGIN_TYPE.PHONE_LOGIN,
                    message: '手机号是必填项!',
                  },
                  {
                    validator: verifyMobile,
                    message: '不合法的手机号!',
                  },
                ]}>
                <Input
                  allowClear
                  size='large'
                  prefix={
                    <MobileOutlined
                      className='site-form-item-icon'
                      style={{ color: '#1890ff' }}
                    />
                  }
                  placeholder='请输入手机号!'
                />
              </Form.Item>
              <Row style={{ width: '100%' }}>
                <Col flex='2 1' style={{ margin: '0px 8px 0px 0px' }}>
                  <Form.Item
                    name='code'
                    rules={[
                      {
                        required: loginMethod === LOGIN_TYPE.PHONE_LOGIN,
                        message: '验证码是必填项!',
                      },
                      {
                        validator: verifyCode,
                        message: '验证码是六位数！',
                      },
                    ]}>
                    <Input
                      size='large'
                      prefix={
                        <MailOutlined
                          className='site-form-item-icon'
                          style={{ color: '#1890ff' }}
                        />
                      }
                      placeholder='请输入验证码!'></Input>
                  </Form.Item>
                </Col>
                <Col
                  flex='1 2'
                  style={{ float: 'right', marginBottom: '24px' }}>
                  <Button
                    disabled={!!countdown}
                    size='large'
                    loading={codeBtnLoading}
                    onClick={() =>
                      handleSendSmsCode(
                        form.getFieldsValue().phoneNumber,
                        opType.login,
                      )
                    }>
                    {countdown ? `${countdown}秒后重新获取` : '获取验证码'}
                  </Button>
                </Col>
              </Row>
            </>
          )}
          <div>
            <Form.Item>
              <Button
                type='link'
                style={{ float: 'right' }}
                onClick={goToRegister}>
                没有账号？立即注册
              </Button>
            </Form.Item>
          </div>
          <Form.Item>
            <Button
              type='primary'
              htmlType='submit'
              className='login-form-button'
              style={{ width: '100%' }}
              loading={submitBtnloading}
              size='large'>
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default App;
